package com.hexacta.hrs.domain.feedback.resultcalculations;

import java.util.Date;

import org.apache.commons.collections.CollectionUtils;

public class Calculator {

	private CalculationSettings settings;
	
	public Calculator() {
		this.settings = new CalculationSettings();
	}
	
	private Long calculateActualAcumulated(String actualRol, Long actualPosition) {
		
		Long actualAcumulatedBandNormalization = null;
		for (Long key : this.settings.getAcumulatedBandNormalization().keySet()) {
			if (this.settings.getAcumulatedBandNormalization().get(key).equals(actualRol)) {
				actualAcumulatedBandNormalization = key;
				break;
			}
		};
		
		Long actualBandNormalization = this.settings.getBandNormalization().get(actualRol);

		Double result = new Double(actualAcumulatedBandNormalization.doubleValue() + (actualPosition.doubleValue() / 100) * actualBandNormalization.doubleValue());
		
		return Math.round(result);
	}
	
	private Long calculateNewAcumulated(String actualRol, Long actualPosition, Date start, Date finish, String score) {
		
		Long growNormalization = this.settings.getGrowScoreNormalization().get(score);
		Double evaluatedDays = (new Double(finish.getTime()) - new Double(start.getTime())) / (24 * 60 * 60 * 1000);
		Long actualAcumulated = this.calculateActualAcumulated(actualRol, actualPosition);
		
		Double result = new Double((growNormalization.doubleValue() * evaluatedDays / 365) + actualAcumulated.doubleValue());
		
		return Math.round(result);
	}
	
	public String getNewBand(String actualRol, Long actualPosition, Date start, Date finish, String score) {
		Long newAcumulated = this.calculateNewAcumulated(actualRol, actualPosition, start, finish, score);
		
		Long[] acumulateds = this.settings.getAcumulatedBandNormalization().keySet().toArray(new Long[0]);
		
		CollectionUtils.reverseArray(acumulateds);
		
		for (Long acumulated : acumulateds) {
			if (newAcumulated >= acumulated) {
				return this.settings.getAcumulatedBandNormalization().get(acumulated);
			}
		}
		return "INDEFINIDO";
	}
	
	public Long getNewPosition(String actualRol, Long actualPosition, Date start, Date finish, String score) {
		String newRol = this.getNewBand(actualRol, actualPosition, start, finish, score);
		Long newAcumulated = this.calculateNewAcumulated(actualRol, actualPosition, start, finish, score);
		
		Long actualAcumulatedBandNormalization = null;
		for (Long key : this.settings.getAcumulatedBandNormalization().keySet()) {
			if (this.settings.getAcumulatedBandNormalization().get(key).equals(newRol)) {
				actualAcumulatedBandNormalization = key;
				break;
			}
		};
		
		Long newBandnormalization = this.settings.getBandNormalization().get(newRol);
		
		Double result = new Double((newAcumulated.doubleValue() - actualAcumulatedBandNormalization.doubleValue()) / newBandnormalization.doubleValue() * 100);
		
		//return Math.round(result);
		return result.longValue();
	}
	
}
